<template>
  <el-form-item
    class="form_engine_item"
    :style="cssVars"
    :label="item.label"
    :prop="item.field"
    :rules="item.rules">
    <component
      :is="getComponent(item)"
      v-model="formData[item.field]"
      v-bind="getComponentProps(item)"
      @change="handleChange"
    />
  </el-form-item>
</template>
<script setup>
import { computed } from 'vue'
import {
  ElInput,
  ElDatePicker,
  ElCheckbox,
  ElRadio,
  ElSwitch
} from 'element-plus';
import SelectInput from './fields/SelectInput.vue'

const { item, formData, fieldWidth } = defineProps({
  item: { type: Object, default: () => ({}) },
  formData: { type: Object, default: () => ({}) },
  fieldWidth: { type: String, default: '220px' }
})



const fieldComponentsMap = {
  input: ElInput,
  select: SelectInput,
  datePicker: ElDatePicker,
  checkbox: ElCheckbox,
  radio: ElRadio,
  switch: ElSwitch
}
// 根据type获取组件
function getComponent(item) {
  return fieldComponentsMap[item.type] || ElInput;
}

// 绑定传进来的props
function getComponentProps(item) {
  const baseProps = {
    placeholder: item.placeholder || `请输入${item.label}`,
    clearable: item.clearable || false, // 可清空
    ...item.props // 合并其他props
  }
  // 下拉组件特别处理
  if (item.type === 'select') {
    baseProps.options = item.options || []; // 下拉选项
  }
  return baseProps;
}

const emit = defineEmits(['change'])
const handleChange = (value) => {
  emit('change', item.field, value);
}


// 动态设置宽度
const cssVars = computed(() => ({
  '--form-item-width': fieldWidth
}));


</script>
<style scoped lang="scss">
.form_engine_item {
  width: var(--form-item-width);
}
</style>